// 创建用户相关的小仓库
import {defineStore} from "pinia";
import {reqLogin, reqUserInfo, reqLogout} from "@/api/system/user/SysUserApi";
import {UserState} from "@/store/modules/types/type.ts";
import {SET_TOKEN, GET_TOKEN, REMOVE_TOKEN} from "@/utils/token.ts";
import {loginForm, loginResponse, userInfoResponse} from "@/api/system/user/type.ts";
// 引入路由（常量路由）
import {constantRoute} from "@/router/routes";

// 创建用户小仓库
const useUserStore = defineStore('user', {
    // 小仓库存储数据地方
    state: (): UserState => {
        return {
            token: GET_TOKEN(),//用户唯一标识token
            menuRoutes: constantRoute,//仓库存储菜单
            username: '', // 用户名
            avatar: '' // 用户头像
        }
    },
    // 异步|逻辑的地方
    actions: {
        // 用户登录方法
        async userLogin(data: loginForm) {
            let result: loginResponse = await reqLogin(data);
            if (result.code == 200) {
                this.token = (result.data as string);
                SET_TOKEN(result.data as string);
                return 'ok';
            } else {
                return Promise.reject(new Error(result.data));
            }
        },
        async userInfo() {
            if (this.token != null) {
                let result: userInfoResponse = await reqUserInfo();
                if (result.code == 200) {
                    this.username = result.data.name;
                    this.avatar = result.data.avatar;
                } else {
                    return Promise.reject(new Error(result.message));
                }
            }
        },
        async logout() {
            let result: any = await reqLogout();
            if (result.code == 200) {
                this.token = '';
                this.username = '';
                this.avatar = '';
                REMOVE_TOKEN();
                return 'OK';
            } else {
                return Promise.reject(new Error(result.message));
            }

        }
    },
    getters: {}
})

export default useUserStore;

